package com.lznAdmin.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lznAdmin.system.entity.SysUser;
import com.lznAdmin.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @program: lznAdmin-pro
 * @description: MybatisPlus自动填充配置类
 * @author: lzn
 * @create: 2022-02-10 15:44
 **/
@Slf4j
@Configuration
public class AutoFillConfig implements MetaObjectHandler {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 插入时自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {

        SysUser userDetails = getUserDetails();
        log.info("插入时自动填充 {}", userDetails.toString());
        this.setFieldValByName("createBy", userDetails.getNickName(), metaObject);
        this.setFieldValByName("updateBy", userDetails.getNickName(), metaObject);
    }

    /**
     * 更新时自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        SysUser userDetails = getUserDetails();
        log.info("更新时自动填充 {}", userDetails.toString());
        this.setFieldValByName("updateBy", userDetails.getNickName(), metaObject);
    }

    /**
     * 获取当前登录用户详细信息
     *
     * @return SysUser
     */
    public SysUser getUserDetails() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return sysUserService.findByUsername(authentication.getName());
    }

}
